package com.example.javamaday.leetcode;

public class LeetCodeTest0067 {

    public static void main(String[] args) {
        System.out.println(addBinary("1", "0"));
    }


    public static String addBinary(String a, String b) {
        char[] charsA = a.toCharArray();
        char[] charsB = b.toCharArray();
        int baseLength = Math.max(charsA.length, charsB.length) + 1;
        char[] result = new char[baseLength];
        int revertIndex = 0;
        boolean needPlus = false;
        while (revertIndex < baseLength) {
            int intA;
            if (charsA.length - 1 - revertIndex >= 0) {
                intA = Integer.parseInt(String.valueOf(charsA[charsA.length - 1 - revertIndex]));
            } else {
                intA = 0;
            }
            int intB;
            if (charsB.length - 1 - revertIndex >= 0) {
                intB = Integer.parseInt(String.valueOf(charsB[charsB.length - 1 - revertIndex]));
            } else {
                intB = 0;
            }
            if (intA + intB == 2) {
                if (needPlus) {
                    result[baseLength - 1 - revertIndex] = '1';
                } else {
                    result[baseLength - 1 - revertIndex] = '0';
                }
                needPlus = true;
            } else if (intA + intB == 1) {
                if (needPlus) {
                    result[baseLength - 1 - revertIndex] = '0';
                    needPlus = true;
                } else {
                    result[baseLength - 1 - revertIndex] = '1';
                    needPlus = false;
                }
            } else if (intA + intB == 0) {
                if (needPlus) {
                    result[baseLength - 1 - revertIndex] = '1';
                } else {
                    result[baseLength - 1 - revertIndex] = '0';
                }
                needPlus = false;
            }
            revertIndex++;
        }

        String resultStr = String.valueOf(result);
        while (resultStr.startsWith("0") && resultStr.length() > 1) {
            resultStr = resultStr.replaceFirst("0", "");
        }
        return resultStr;
    }
}
